class ApprovalsController < ApplicationController

  def create    
    jm = params[:jm]
    proposal = Proposal.find(params[:proposal])
    
    if jm != nil
      jurisdiction_member = JurisdictionMember.find(jm)
      give_approval jurisdiction_member, proposal
    else
      give_final_approval proposal  
    end    
  end
  
  def give_approval jurisdiction_member, proposal    
    approvals = Approval.find_all_by_jurisdiction_id_and_role_id_and_proposal_id(jurisdiction_member.jurisdiction.id, jurisdiction_member.role.id, proposal.id)    
    if (approvals.size == 0)
      approval = Approval.new
      approval.jurisdiction = jurisdiction_member.jurisdiction
      approval.role = jurisdiction_member.role
      approval.user = jurisdiction_member.user
      approval.proposal = proposal      
      approval.save
    end
    
    approvals = Approval.find_all_by_proposal_id(proposal.id)
    
    if approvals.size == 6
      proposal.approve!
      redirect_to proposals_path
    else
      redirect_to proposal_path(proposal.id)
    end      
  end
  
  def give_final_approval proposal
    proposal.approve!
    redirect_to proposals_path
  end
  
end
